﻿Imports System.Text
Imports System.Threading
Imports System.Web
Imports System.Runtime.InteropServices
Imports Sy.Data
Imports Sy.UI.Common

Public Class Frm_amazonkeywords
    Dim allkey As New Collection
    Dim nallkey As String
    Dim kwd As String
    Dim nurl As String = ""
    Dim ngj As String = ""
    Dim uploadxc As Thread
    Dim isworking As Boolean = False
    Private Sub Frm_amazonkeywords_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Create = CreateSQLBuilder(Of TaskList6).CreateSQL()
        DB = New SQLite(Create, Application.StartupPath & "\Config\task6.db")
        TaskList6.AddDB(DB)
        DB.Foreign_keys = True
        UIAdapter.ListviewAdapter(Of TaskList6)(ListView1, "序号")
        Loadlist("")

        Country.Items.Add("Amazon.com")
        Country.Items.Add("Amazon.ca")
        Country.Items.Add("Amazon.com.mx")
        Country.Items.Add("Amazon.co.uk")
        Country.Items.Add("Amazon.in")
        Country.Items.Add("Amazon.fr")
        Country.Items.Add("Amazon.de")
        Country.SelectedIndex = 0

    End Sub
    Sub Loadlist(sqlstr As String)
        Try
            With ListView1
                .Items.Clear()
            End With
            Dim TaskLists = If(sqlstr.IsNotWhiteSpace, TaskList6.LoadWhere(sqlstr), TaskList6.Load())
            Dim i As Long = 1
            For Each TaskList In TaskLists
                Dim a = UIAdapter.GetListViewItem(TaskList, i)
                Dim itm As ListViewItem = ListView1.Items.Add(a) '状态 进度 id
                itm.Tag = TaskList
                i = i + 1
            Next
        Catch ex As Exception
            MsgBox("加载数据异常", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
        Try
            If Trim(keywd.Text) = "" Then
                MsgBox("关键词不能为空")
                Exit Sub
            End If
            isworking = True
            allkey.Clear()
            shuchu.Text = ""
            ngj = Country.Text
            nallkey = ""
            ListView1.Items.Clear()
            kwd = keywd.Text
            btnstart.Enabled = False
            nurl = "https://api.sellerapp.com/amazon/" & getcountrycode(Country.Text) & "/free_tool/keyword/search_v3"
            uploadxc = New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf caiji))
            uploadxc.Name = NameOf(caiji)
            uploadxc.Start()   '启动线程
            btnstop.Enabled = True
        Catch ex As Exception
            MsgBox("发生异常，已经停止")
            btnstop.Enabled = False
            btnstart.Enabled = True
        End Try
    End Sub
    Sub caiji()
        Try
            Do
                Dim postdata = Sy.Net.PostDataBuilder
                'postdata.Add("accept", "application/json, text/plain, */*")
                'postdata.Add("accept", "application/json, text/plain, */*")
                If allkey.Count > 0 Then
                    Dim jkey = allkey(1).ToString
                    allkey.Remove(1)
                    postdata.Add("{""keyword"" : """ & jkey & """}")
                Else
                    postdata.Add("{""keyword"" : """ & kwd & """}")
                End If
                Dim Res = Sy.Net.Factory.Http(nurl).SetAccept("application/json, text/plain, */*").SetContentType("application/json").SetOrigin("https://www.sellerapp.com").SetReferer("https://www.sellerapp.com/").SetKeepAlive(False).SetPostDataBuilder(postdata).Post()
                Dim Obj = Jsonkey.Deserialize(Res)
                'Console.WriteLine(Res)
                'Console.WriteLine(Obj.keywords)
                Try
                    If Obj.IsNotNull() Then
                        Dim nkeyw = Obj.keywords
                        For i = 0 To nkeyw.Count - 1
                            Dim mkeyw = nkeyw(i).keyword
                            Dim searches = nkeyw(i).sa_metrics.searches
                            Dim purchases = nkeyw(i).sa_metrics.purchases
                            Dim matches = nkeyw(i).sa_metrics.matches
                            Dim lb As Decimal = nkeyw(i).googletarget.cpc.lb
                            Dim ub As Decimal = nkeyw(i).googletarget.cpc.ub
                            Dim cpc = "$" & Decimal.Round(lb, 2) & " - $" & Decimal.Round(ub, 2)
                            If InStr(nallkey, mkeyw) <= 0 Then
                                allkey.Add(mkeyw)
                                nallkey &= mkeyw & vbCrLf
                                Dim t As New TaskList6
                                t.gj = ngj
                                t.keyword = mkeyw
                                t.searchs = searches
                                t.orders = purchases
                                t.products = matches
                                t.cpc = cpc
                                t.Add()

                                Invoke(Sub()
                                           Dim itm As ListViewItem
                                           itm = ListView1.Items.Add(ListView1.Items.Count + 1)
                                           itm.SubItems.AddRange({CStr(ngj), CStr(mkeyw), CStr(searches), CStr(cpc), CStr(purchases), CStr(matches)})
                                           shuchu.Text &= "获取到关键词：" & mkeyw & vbCrLf
                                       End Sub)
                            End If
                        Next
                    End If
                Catch ex As Exception
                    Thread.Sleep(5000)
                End Try
                Thread.Sleep(5000)
            Loop
        Catch ex As Exception
            Invoke(Sub()
                       'MsgBox("发生异常，已经停止")
                       shuchu.Text &= "已经停止" & vbCrLf
                       btnstop.Enabled = False
                       btnstart.Enabled = True
                   End Sub)
        End Try
    End Sub
    Function getcountrycode(str As String) As String
        If str = "Amazon.com" Then
            Return "us"
        ElseIf str = "Amazon.ca" Then
            Return "ca"
        ElseIf str = "Amazon.com.mx" Then
            Return "mx"
        ElseIf str = "Amazon.co.uk" Then
            Return "uk"
        ElseIf str = "Amazon.fr" Then
            Return "fr"
        ElseIf str = "Amazon.de" Then
            Return "de"
        Else
            Return "us"
        End If
    End Function

    Private Sub btnstop_Click(sender As Object, e As EventArgs) Handles btnstop.Click
        Try
            isworking = False
            If uploadxc.IsAlive Then
                uploadxc.Abort()
            End If
            GC.Collect()
            GC.WaitForFullGCApproach()
            btnstop.Enabled = False
            btnstart.Enabled = True
            Loadlist("")
            MsgBox("已经停止", MsgBoxStyle.OkOnly, "提示")
        Catch ex As Exception
            btnstop.Enabled = False
            btnstart.Enabled = True
            isworking = False
            MsgBox("已经停止", MsgBoxStyle.OkOnly, "提示")
            Loadlist("")
        End Try
    End Sub

    Private Sub shuchu_TextChanged(sender As Object, e As EventArgs) Handles shuchu.TextChanged
        Try
            If UBound(Split(shuchu.Text, vbCrLf)) > 9 Then
                shuchu.Text = Mid(shuchu.Text, InStr(shuchu.Text, vbCrLf) + 2)
            End If
            shuchu.SelectionStart = Len(shuchu.Text)
            shuchu.ScrollToCaret()
        Catch ex As Exception
            MsgBox("状态输出异常！", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Try
            For i = 0 To ListView1.Items.Count - 1
                If ListView1.Items(i).Checked = True Then
                    'DB.Execute("delete from tasklist where ID='" & ListView2.Items(i).SubItems(1).Text & "'")
                    Dim TaskList As TaskList6 = ListView1.Items(i).Tag
                    TaskList.Del()
                End If
            Next
            Call Loadlist("")
        Catch ex As Exception
            MsgBox("删除出错", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try
            Dim TaskList As TaskList6
            TaskList6.Execute("delete from t_TaskList6 where 1=1")
            Loadlist("")
        Catch ex As Exception
            MsgBox("删除出错", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then
            For I = 0 To ListView1.Items.Count - 1
                ListView1.Items(I).Checked = True
            Next
        Else
            For I = 0 To ListView1.Items.Count - 1
                ListView1.Items(I).Checked = False
            Next
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Loadlist("")
    End Sub

    Private Sub Country_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Country.SelectedIndexChanged
        Dim sqlstr = "1=1 and gj='" & Country.Text & "'"
        Loadlist(sqlstr)
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Try
            For i = 0 To ListView1.Items.Count - 1
                If ListView1.Items(i).Checked = True Then
                    'DB.Execute("delete from tasklist where ID='" & ListView2.Items(i).SubItems(1).Text & "'")
                    TextBox2.Text &= ListView1.Items(i).SubItems(2).Text & vbCrLf
                End If
            Next
        Catch ex As Exception
            MsgBox("操作出错", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Try
            Dim sqlstr = "1=1 order by searchs asc"
            Loadlist(sqlstr)
        Catch ex As Exception
            MsgBox("操作出错", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        Try
            Dim sqlstr = "1=1 order by searchs desc"
            Loadlist(sqlstr)
        Catch ex As Exception
            MsgBox("操作出错", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim postdata = Sy.Net.PostDataBuilder
        postdata.Add("{""keyword"" : ""dress""}")
        Dim ippeo As Sy.Net.ProxyPool_ZhiMa
        ippeo.GetProxy()

        Dim Res = Sy.Net.Factory.Http(nurl).SetAccept("application/json, text/plain, */*").SetContentType("application/json").SetOrigin("https://www.sellerapp.com").SetReferer("https://www.sellerapp.com/").SetKeepAlive(False).SetProxy(ippeo).SetPostDataBuilder(postdata).Post()
        Console.WriteLine(Res)
    End Sub
End Class